//
//  HomeViewController.m
//  CangLongWnnianli
//
//  Created by 暗流澎涌 on 2025/7/2.
//

#import "HomeViewController.h"
#import "CalendarDetailViewController.h"
#import "LuckyDayViewController.h"
#import "CalendarViewController.h"

#import "ProfileViewController.h"
#import "HuangliModel.h"
#import <Masonry/Masonry.h>

@interface HomeViewController ()

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *weatherCard;
@property (nonatomic, strong) UIView *calendarCard;
@property (nonatomic, strong) UIView *functionGrid;
@property (nonatomic, strong) UIView *bottomNav;

@property (nonatomic, strong) UIButton *detailButton;
@property (nonatomic, strong) UIView *headerTopView;

// 新增属性用于日期控制
@property (nonatomic, strong) NSDate *currentDate;
@property (nonatomic, strong) UIView *dateControlContainer;
@property (nonatomic, strong) UILabel *dateDisplayLabel;
@property (nonatomic, strong) UILabel *weekdayLabel;
@property (nonatomic, strong) UIButton *previousDayButton;
@property (nonatomic, strong) UIButton *nextDayButton;
@property (nonatomic, strong) UIButton *todayButton;

// 新增日历相关属性
@property (nonatomic, strong) NSDate *displayedMonth;
@property (nonatomic, strong) UILabel *monthYearLabel;
@property (nonatomic, strong) UIView *weekdayHeaderView;
@property (nonatomic, strong) UIView *datesGridView;
//@property (nonatomic, strong) NSMutableArray *dateButtons;

@property (nonatomic, strong) UIView *calendarView;



@property (nonatomic, strong) NSMutableArray<UIButton *> *dateButtons;

@property (nonatomic, strong) UIButton *selectedDateButton;


@end

@implementation HomeViewController

- (void)viewDidLoad {
    self.edgesForExtendedLayout = UIRectEdgeAll;
    self.extendedLayoutIncludesOpaqueBars = YES;
    [super viewDidLoad];
    
    // 初始化当前日期
    self.currentDate = [NSDate date];
    
    // 设置状态栏背景色
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
    statusBarView.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    [self.view addSubview:statusBarView];
    [self setupUI];
    [self loadHuangliDataForDate:self.currentDate];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor colorWithRed:0.941 green:0.949 blue:0.961 alpha:1.0];
    
    // 滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    
    // 内容视图
    self.contentView = [[UIView alloc] init];
    [self.scrollView addSubview:self.contentView];
    
    // 创建各个组件
    [self createHeaderView];
    [self createWeatherCard];
    [self createCalendarCard];
    [self createFunctionGrid];
//    [self createBottomNav];
    [self setupConstraints];
    
}

- (void)createHeaderView {
    self.headerView = [[UIView alloc] init];
//    
//    // 创建渐变背景
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    gradientLayer.colors = @[
//        (id)[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0].CGColor,
//        (id)[UIColor colorWithRed:0.839 green:0.220 blue:0.220 alpha:1.0].CGColor
//    ];
//    gradientLayer.startPoint = CGPointMake(0, 0);
//    gradientLayer.endPoint = CGPointMake(1, 1);
//    [self.headerView.layer insertSublayer:gradientLayer atIndex:0];
    
    self.headerTopView = [[UIView alloc] init];
//    // 创建新的渐变层给headerTopView
//    CAGradientLayer *topGradientLayer = [CAGradientLayer layer];
//    topGradientLayer.colors = @[
//        (id)[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0].CGColor,
//        (id)[UIColor colorWithRed:0.839 green:0.220 blue:0.220 alpha:1.0].CGColor
//    ];
//    topGradientLayer.startPoint = CGPointMake(0, 0);
//    topGradientLayer.endPoint = CGPointMake(1, 1);
//    [self.headerTopView.layer insertSublayer:topGradientLayer atIndex:0];
    self.headerTopView.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    [self.view addSubview:self.headerTopView];
    
    // 添加"万年历"标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"黄历详情";
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerTopView addSubview:titleLabel];
    
    // 设置标题约束
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.headerTopView);
        make.centerY.equalTo(self.headerTopView).offset(10);
    }];
    
    // 在viewDidLayoutSubviews中设置渐变层frame
//    dispatch_async(dispatch_get_main_queue(), ^{
//        topGradientLayer.frame = self.headerTopView.bounds;
//    });
}

- (void)createDateControlContainer {
    // 日期控制容器 - 扩大高度以容纳日历
    self.dateControlContainer = [[UIView alloc] init];
    self.dateControlContainer.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.95];
    self.dateControlContainer.layer.cornerRadius = 20;
    self.dateControlContainer.layer.borderWidth = 1;
    self.dateControlContainer.layer.borderColor = [UIColor colorWithWhite:0.9 alpha:1.0].CGColor;
    self.dateControlContainer.layer.shadowColor = [UIColor blackColor].CGColor;
    self.dateControlContainer.layer.shadowOffset = CGSizeMake(0, 2);
    self.dateControlContainer.layer.shadowOpacity = 0.1;
    self.dateControlContainer.layer.shadowRadius = 8;
    [self.contentView addSubview:self.dateControlContainer];
    
    // 初始化显示月份为当前月份
    self.displayedMonth = [NSDate date];
    self.dateButtons = [[NSMutableArray alloc] init];
    
    [self createCalendarHeader];
    [self createCalendarView];
}

- (void)createCalendarHeader {
    // 左箭头按钮 - 切换到上个月
    self.previousDayButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.previousDayButton.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.1];
    [self.previousDayButton setTitle:@"‹" forState:UIControlStateNormal];
    [self.previousDayButton setTitleColor:[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0] forState:UIControlStateNormal];
    self.previousDayButton.titleLabel.font = [UIFont systemFontOfSize:24 weight:UIFontWeightMedium];
    self.previousDayButton.layer.cornerRadius = 18;
    self.previousDayButton.layer.borderWidth = 1;
    self.previousDayButton.layer.borderColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.2].CGColor;
    [self.previousDayButton addTarget:self action:@selector(previousMonthTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.dateControlContainer addSubview:self.previousDayButton];
    
    // 右箭头按钮 - 切换到下个月
    self.nextDayButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextDayButton.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.1];
    [self.nextDayButton setTitle:@"›" forState:UIControlStateNormal];
    [self.nextDayButton setTitleColor:[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0] forState:UIControlStateNormal];
    self.nextDayButton.titleLabel.font = [UIFont systemFontOfSize:24 weight:UIFontWeightMedium];
    self.nextDayButton.layer.cornerRadius = 18;
    self.nextDayButton.layer.borderWidth = 1;
    self.nextDayButton.layer.borderColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.2].CGColor;
    [self.nextDayButton addTarget:self action:@selector(nextMonthTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.dateControlContainer addSubview:self.nextDayButton];
    
    // 月份年份显示标签
    self.monthYearLabel = [[UILabel alloc] init];
    self.monthYearLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightBold];
    self.monthYearLabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
    self.monthYearLabel.textAlignment = NSTextAlignmentCenter;
    [self.dateControlContainer addSubview:self.monthYearLabel];
    
    // 设置头部约束
    [self.previousDayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dateControlContainer).offset(15);
        make.top.equalTo(self.dateControlContainer).offset(15);
        make.width.height.mas_equalTo(36);
    }];
    
    [self.nextDayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.dateControlContainer).offset(-15);
        make.top.equalTo(self.dateControlContainer).offset(15);
        make.width.height.mas_equalTo(36);
    }];
    
    [self.monthYearLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.dateControlContainer);
        make.centerY.equalTo(self.previousDayButton);
        make.left.equalTo(self.previousDayButton.mas_right).offset(10);
        make.right.equalTo(self.nextDayButton.mas_left).offset(-10);
    }];
}

- (void)createCalendarView {
    // 星期标题行
    self.weekdayHeaderView = [[UIView alloc] init];
    [self.dateControlContainer addSubview:self.weekdayHeaderView];
    
    NSArray *weekdays = @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];
    for (int i = 0; i < weekdays.count; i++) {
        UILabel *weekdayLabel = [[UILabel alloc] init];
        weekdayLabel.text = weekdays[i];
        weekdayLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        weekdayLabel.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
        weekdayLabel.textAlignment = NSTextAlignmentCenter;
        [self.weekdayHeaderView addSubview:weekdayLabel];
        
        [weekdayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.weekdayHeaderView);
            make.width.equalTo(self.weekdayHeaderView).dividedBy(7);
            if (i == 0) {
                make.left.equalTo(self.weekdayHeaderView);
            } else {
                UILabel *previousLabel = [self.weekdayHeaderView.subviews objectAtIndex:i-1];
                make.left.equalTo(previousLabel.mas_right);
            }
        }];
    }
    
    // 日期网格视图
    self.datesGridView = [[UIView alloc] init];
    [self.dateControlContainer addSubview:self.datesGridView];
    
    // 创建42个日期按钮（6行7列）
    for (int i = 0; i < 42; i++) {
        UIButton *dateButton = [UIButton buttonWithType:UIButtonTypeCustom];
        dateButton.titleLabel.font = [UIFont systemFontOfSize:16];
        dateButton.layer.cornerRadius = 18;
        [dateButton addTarget:self action:@selector(dateButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [self.datesGridView addSubview:dateButton];
        [self.dateButtons addObject:dateButton];
        
        int row = i / 7;
        int col = i % 7;
        
        [dateButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(36);
            // 使用与weekdayLabel相同的布局方式
            make.width.equalTo(self.datesGridView).dividedBy(7);
            if (col == 0) {
                make.left.equalTo(self.datesGridView);
            } else {
                UIButton *previousButton = [self.dateButtons objectAtIndex:i-1];
                make.left.equalTo(previousButton.mas_right);
            }
            make.top.equalTo(self.datesGridView).offset(row * 40);
        }];
    }
    
    // 设置日历视图约束 - 修改边距为12
    [self.weekdayHeaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.dateControlContainer).inset(12); // 改为12像素边距
        make.top.equalTo(self.monthYearLabel.mas_bottom).offset(15);
        make.height.mas_equalTo(30);
    }];
    
    [self.datesGridView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.dateControlContainer).inset(12); // 改为12像素边距
        make.top.equalTo(self.weekdayHeaderView.mas_bottom).offset(10);
        make.height.mas_equalTo(240); // 6行 * 40高度
        make.bottom.equalTo(self.dateControlContainer).offset(-15);
    }];
    
    [self updateCalendarDisplay];
}

- (void)createWeatherCard {
    // 先创建日期控制容器
    [self createDateControlContainer];
    
    self.weatherCard = [[UIView alloc] init];
    self.weatherCard.backgroundColor = [UIColor whiteColor];
    self.weatherCard.layer.cornerRadius = 12;
    self.weatherCard.layer.shadowColor = [UIColor blackColor].CGColor;
    self.weatherCard.layer.shadowOffset = CGSizeMake(0, 2);
    self.weatherCard.layer.shadowOpacity = 0.1;
    self.weatherCard.layer.shadowRadius = 4;
    [self.contentView addSubview:self.weatherCard];
}

- (void)createCalendarCard {
    self.calendarCard = [[UIView alloc] init];
    self.calendarCard.backgroundColor = [UIColor whiteColor];
    self.calendarCard.layer.cornerRadius = 12;
    self.calendarCard.layer.shadowColor = [UIColor blackColor].CGColor;
    self.calendarCard.layer.shadowOffset = CGSizeMake(0, 2);
    self.calendarCard.layer.shadowOpacity = 0.1;
    self.calendarCard.layer.shadowRadius = 4;
    [self.contentView addSubview:self.calendarCard];
    
    // 头部
    UIView *cardHeader = [[UIView alloc] init];
    cardHeader.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    cardHeader.layer.cornerRadius = 12;
    cardHeader.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    [self.calendarCard addSubview:cardHeader];
    
    UILabel *lunarDate = [[UILabel alloc] init];
    lunarDate.text = @"农历九月初一";
    lunarDate.font = [UIFont boldSystemFontOfSize:20];
    lunarDate.textColor = [UIColor whiteColor];
    lunarDate.tag = 1001; // 农历日期标签
    [cardHeader addSubview:lunarDate];
    
    UILabel *ganzhi = [[UILabel alloc] init];
    ganzhi.text = @"---";
    ganzhi.font = [UIFont systemFontOfSize:14];
    ganzhi.textColor = [UIColor colorWithRed:0.996 green:0.988 blue:0.749 alpha:1.0];
    ganzhi.tag = 1002; // 干支标签
    [cardHeader addSubview:ganzhi];
    
    UIView *dayCircle = [[UIView alloc] init];
    dayCircle.backgroundColor = [UIColor colorWithRed:0.839 green:0.620 blue:0.180 alpha:1.0];
    dayCircle.layer.cornerRadius = 20;
    [cardHeader addSubview:dayCircle];
    
    UILabel *dayLabel = [[UILabel alloc] init];
    dayLabel.text = @"15";
    dayLabel.font = [UIFont boldSystemFontOfSize:18];
    dayLabel.textColor = [UIColor whiteColor];
    dayLabel.textAlignment = NSTextAlignmentCenter;
    dayLabel.tag = 1003; // 日期标签
    [dayCircle addSubview:dayLabel];
    
    [cardHeader mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.calendarCard);
        make.height.mas_equalTo(80);
    }];
    
    [lunarDate mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cardHeader).offset(16);
        make.top.equalTo(cardHeader).offset(16);
    }];
    
    [ganzhi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lunarDate);
        make.top.equalTo(lunarDate.mas_bottom).offset(4);
    }];
    
    [dayCircle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(cardHeader).offset(-16);
        make.centerY.equalTo(cardHeader);
        make.width.height.mas_equalTo(40);
    }];
    
    [dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(dayCircle);
    }];
    
    // 宜忌内容
    UIView *contentView = [[UIView alloc] init];
    contentView.tag = 3001;
    [self.calendarCard addSubview:contentView];
    
    // 宜
    UILabel *yiTitle = [[UILabel alloc] init];
    yiTitle.text = @"宜";
    yiTitle.font = [UIFont boldSystemFontOfSize:16];
    yiTitle.textColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    [contentView addSubview:yiTitle];
    
    // 忌
    UILabel *jiTitle = [[UILabel alloc] init];
    jiTitle.text = @"忌";
    jiTitle.font = [UIFont boldSystemFontOfSize:16];
    jiTitle.textColor = [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0];
    [contentView addSubview:jiTitle];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cardHeader.mas_bottom);
        make.left.right.bottom.equalTo(self.calendarCard);
    }];
    
    [yiTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(contentView).offset(16);
    }];
    
    [jiTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView).offset(16);
        make.top.equalTo(yiTitle.mas_bottom).offset(40); // 先临时放下，后续会被动态布局覆盖
    }];
    
    // 查看详情按钮
    self.detailButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.detailButton setTitle:@"查看详细黄历" forState:UIControlStateNormal];
    [self.detailButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.detailButton.titleLabel.font = [UIFont systemFontOfSize:16];
    self.detailButton.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
    self.detailButton.layer.cornerRadius = 8;
    [self.detailButton addTarget:self action:@selector(calendarDetailTapped) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:self.detailButton];
    
    [self.detailButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(contentView).inset(16);
        make.top.equalTo(jiTitle.mas_bottom).offset(16);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(contentView).offset(-16);
    }];
}

- (UIView *)createItemsContainer:(NSArray *)items color:(UIColor *)bgColor textColor:(UIColor *)textColor {
    UIView *container = [[UIView alloc] init];
    UIView *lastLabel = nil;
    UIView *lastRowFirstLabel = nil;
    CGFloat maxWidth = UIScreen.mainScreen.bounds.size.width - 64;
    CGFloat itemHeight = 28;
    CGFloat itemSpacing = 8;
    CGFloat lineSpacing = 8;
    CGFloat currentRowWidth = 0;

    for (int i = 0; i < items.count; i++) {
        NSString *item = items[i];
        UILabel *itemLabel = [[UILabel alloc] init];
        itemLabel.text = item;
        itemLabel.font = [UIFont systemFontOfSize:14];
        itemLabel.textColor = textColor;
        itemLabel.backgroundColor = bgColor;
        itemLabel.layer.cornerRadius = 4;
        itemLabel.layer.masksToBounds = YES;
        itemLabel.textAlignment = NSTextAlignmentCenter;
        [container addSubview:itemLabel];

        CGSize textSize = [item sizeWithAttributes:@{NSFontAttributeName: itemLabel.font}];
        CGFloat itemWidth = textSize.width + 16;

        BOOL isNewLine = (!lastLabel || currentRowWidth + itemWidth > maxWidth);

        [itemLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(itemHeight);
            make.width.mas_equalTo(itemWidth);
            if (isNewLine) {
                make.left.equalTo(container);
                if (lastRowFirstLabel) {
                    make.top.equalTo(lastRowFirstLabel.mas_bottom).offset(lineSpacing);
                } else {
                    make.top.equalTo(container);
                }
            } else {
                make.left.equalTo(lastLabel.mas_right).offset(itemSpacing);
                make.top.equalTo(lastLabel);
            }
        }];

        if (isNewLine) {
            currentRowWidth = itemWidth + itemSpacing;
            lastRowFirstLabel = itemLabel;
        } else {
            currentRowWidth += itemWidth + itemSpacing;
        }
        lastLabel = itemLabel;
    }
    // 最后一行bottom
    if (lastLabel) {
        [container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(lastLabel.mas_bottom);
        }];
    }
    return container;
}

- (void)createFunctionGrid {
    self.functionGrid = [[UIView alloc] init];
    [self.contentView addSubview:self.functionGrid];
    
    NSArray *functions = @[
        @{@"title": @"择吉日", @"color": [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.1]},
        @{@"title": @"周公解梦", @"color": [UIColor colorWithRed:0.839 green:0.620 blue:0.180 alpha:0.1]},
//        @{@"title": @"生肖运势", @"color": [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.1]},
        @{@"title": @"节日查询", @"color": [UIColor colorWithRed:0.839 green:0.620 blue:0.180 alpha:0.1]}
    ];
    
    for (int i = 0; i < functions.count; i++) {
        NSDictionary *function = functions[i];
        
        UIView *functionView = [[UIView alloc] init];
        functionView.backgroundColor = [UIColor whiteColor];
        functionView.layer.cornerRadius = 12;
        functionView.layer.shadowColor = [UIColor blackColor].CGColor;
        functionView.layer.shadowOffset = CGSizeMake(0, 2);
        functionView.layer.shadowOpacity = 0.1;
        functionView.layer.shadowRadius = 4;
        [self.functionGrid addSubview:functionView];
        
        UIView *iconContainer = [[UIView alloc] init];
        iconContainer.backgroundColor = function[@"color"];
        iconContainer.layer.cornerRadius = 24;
        [functionView addSubview:iconContainer];
        
        UILabel *iconLabel = [[UILabel alloc] init];
        iconLabel.text = @[@"📅", @"🌙", @"🐉", @"🎁"][i];
        iconLabel.font = [UIFont systemFontOfSize:20];
        iconLabel.textAlignment = NSTextAlignmentCenter;
        [iconContainer addSubview:iconLabel];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = function[@"title"];
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        titleLabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [functionView addSubview:titleLabel];
        
        // 添加点击事件
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(functionTapped:)];
        functionView.tag = i;
        functionView.userInteractionEnabled = YES;
        [functionView addGestureRecognizer:tap];
        
        [functionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo((UIScreen.mainScreen.bounds.size.width - 48) / 2);
            make.height.mas_equalTo(100);
            make.left.equalTo(self.functionGrid).offset((i % 2) * ((UIScreen.mainScreen.bounds.size.width - 48) / 2 + 16));
            make.top.equalTo(self.functionGrid).offset((i / 2) * 116);
        }];
        
        [iconContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(functionView);
            make.top.equalTo(functionView).offset(16);
            make.width.height.mas_equalTo(48);
        }];
        
        [iconLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(iconContainer);
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(functionView);
            make.top.equalTo(iconContainer.mas_bottom).offset(8);
        }];
    }
}

- (void)createBottomNav {
    
}

- (void)setupConstraints {
    [self.headerTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(80);
    }];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(90);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    // 获取导航区高度
    CGFloat statusBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;
    CGFloat navBarHeight = 44.0;
    CGFloat topBarHeight = statusBarHeight + navBarHeight;
//    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.equalTo(self.contentView);
//        make.height.mas_equalTo(88); // 增加高度从40改为88
//    }];
//    [self.headerTopView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.equalTo(self.view);
//            make.height.mas_equalTo(44); // 增加高度从40改为88
//        }];
        
    [self.dateControlContainer mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.headerView.mas_bottom).offset(16);
        make.left.top.right.equalTo(self.contentView).inset(16);
        make.height.mas_equalTo(350); // 增加高度以容纳日历
    }];
    
    [self.weatherCard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.dateControlContainer.mas_bottom).offset(16);
        make.left.right.equalTo(self.contentView).inset(16);
        make.height.mas_equalTo(0);
    }];
    
    [self.calendarCard mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.weatherCard.mas_bottom).offset(16);
        make.left.right.equalTo(self.contentView).inset(16);
    }];
    
    [self.functionGrid mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.calendarCard.mas_bottom).offset(16);
        make.left.right.equalTo(self.contentView).inset(16);
        make.height.mas_equalTo(232);
        make.bottom.equalTo(self.contentView).offset(-16);
    }];
    [self.bottomNav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(80);
    }];
}

#pragma mark - Actions

- (void)calendarDetailTapped {
    CalendarDetailViewController *detailVC = [[CalendarDetailViewController alloc] init];
    detailVC.huangliData = self.currentHuangliData;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}
-(void)gotoCalendarView {
    CalendarViewController *detailVC = [[CalendarViewController alloc] init];
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}
- (void)functionTapped:(UITapGestureRecognizer *)tap {
   
    NSInteger index = tap.view.tag;
    switch (index) {
        case 0:
            [self calendarDetailTapped];
            break;
        case 1:
            [self  showComingSoonAlert:@""];
            break;
        case 2:
            [self  showComingSoonAlert:@""];
            break;
        case 3:
            [self  showComingSoonAlert:@""];
            break;
        default:
            break;
    }
    
    
    
}

- (void)showComingSoonAlert:(NSString *)featureName {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"功能提示"
                                                                   message:[NSString stringWithFormat:@"%@功能暂未开放，敬请期待！", featureName]
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"知道了"
                                                       style:UIAlertActionStyleDefault
                                                     handler:nil];
    [alert addAction:okAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - Data Loading

- (void)loadHuangliDataForDate:(NSDate *)date {
    // 获取指定日期的字符串
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *dateString = [formatter stringFromDate:date];
    
    NSLog(@"正在加载日期: %@ 的黄历数据", dateString);
    
    // 从日期中提取年份
    NSString *year = [dateString substringToIndex:4];
    
    // 构建JSON文件路径
    NSString *fileName = [NSString stringWithFormat:@"huangli_%@.json", year];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    
    // 如果直接找不到，尝试在dataList目录下查找
    if (!filePath) {
        filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil inDirectory:@"dataList"];
    }
    
    if (!filePath) {
        NSLog(@"未找到黄历数据文件: %@", fileName);
        return;
    }
    
    NSLog(@"找到数据文件: %@", filePath);
    
    // 读取JSON文件
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    if (!jsonData) {
        NSLog(@"无法读取黄历数据文件: %@", filePath);
        return;
    }
    
    // 解析JSON
    NSError *error;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    if (error) {
        NSLog(@"JSON解析错误: %@", error.localizedDescription);
        return;
    }
    
    NSLog(@"JSON解析成功，共 %lu 条数据", (unsigned long)jsonArray.count);
    
    // 查找指定日期的数据
    for (NSDictionary *dayData in jsonArray) {
        if ([dayData[@"date"] isEqualToString:dateString]) {
            NSLog(@"找到指定日期数据: %@", dayData);
            self.currentHuangliData = [[HuangliModel alloc] initWithDictionary:dayData];
            [self updateCalendarCardWithHuangliData:self.currentHuangliData];
            break;
        }
    }
}

- (void)loadHuangliDataForCurrentDate {
    [self loadHuangliDataForDate:self.currentDate];
    [self updateTodayButtonVisibility];
}

- (void)updateCalendarCardWithHuangliData:(HuangliModel *)huangliData {
    if (!huangliData) {
        NSLog(@"黄历数据为空，无法更新UI");
        return;
    }
    
    NSLog(@"开始更新UI，农历信息: %@", huangliData.nongli);
    
    // 更新农历日期
    UILabel *lunarDateLabel = [self findLabelWithTag:1001 inView:self.calendarCard];
    if (lunarDateLabel) {
        // 格式化农历日期显示
        NSString *formattedNongli = [self formatNongliString:huangliData.nongli];
        lunarDateLabel.text = formattedNongli;
        NSLog(@"更新农历日期标签: %@", formattedNongli);
    } else {
        NSLog(@"未找到农历日期标签 (tag: 1001)");
    }
    
    // 更新干支信息
    UILabel *ganzhiLabel = [self findLabelWithTag:1002 inView:self.calendarCard];
    if (ganzhiLabel) {
        // 从nongli中提取干支信息
        NSString *formattedNongli = [self formatSecNongliString:huangliData.nongli];
        NSArray *components = [formattedNongli componentsSeparatedByString:@" "];
        if (components.count >= 5) {
            NSString *ganzhi = [NSString stringWithFormat:@"%@ %@ %@", components[3], components[4], components[5]];
            ganzhiLabel.text = ganzhi;
            NSLog(@"更新干支信息: %@", ganzhi);
        }
    } else {
        NSLog(@"未找到干支标签 (tag: 1002)");
    }
    
    // 更新日期圆圈中的数字
    UILabel *dayLabel = [self findLabelWithTag:1003 inView:self.calendarCard];
    if (dayLabel) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSDate *date = [formatter dateFromString:huangliData.date];
        formatter.dateFormat = @"dd";
        NSString *dayString = [formatter stringFromDate:date];
        dayLabel.text = dayString;
        NSLog(@"更新日期数字: %@", dayString);
    } else {
        NSLog(@"未找到日期标签 (tag: 1003)");
    }
    
    // 更新宜忌内容
    [self updateYiJiContentWithHuangliData:huangliData];
}

- (UILabel *)findLabelWithTag:(NSInteger)tag inView:(UIView *)view {
    // 递归查找指定tag的UILabel
    for (UIView *subview in view.subviews) {
        if ([subview isKindOfClass:[UILabel class]] && subview.tag == tag) {
            return (UILabel *)subview;
        }
        UILabel *foundLabel = [self findLabelWithTag:tag inView:subview];
        if (foundLabel) {
            return foundLabel;
        }
    }
    return nil;
}

- (void)updateYiJiContentWithHuangliData:(HuangliModel *)huangliData {
    UIView *contentView = [self.calendarCard viewWithTag:3001];
    if (!contentView) return;
    
    // 禁用自动布局动画
    [UIView setAnimationsEnabled:NO];
    
    // 先移除所有旧的宜/忌容器
    for (UIView *subview in contentView.subviews.copy) {
        if (subview.tag == 2001 || subview.tag == 2002) {
            [subview removeFromSuperview];
        }
    }
    // 找到标题 
    UILabel *yiTitle = nil;
    UILabel *jiTitle = nil;
    for (UIView *subview in contentView.subviews) {
        if ([subview isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)subview;
            if ([label.text isEqualToString:@"宜"]) yiTitle = label;
            if ([label.text isEqualToString:@"忌"]) jiTitle = label;
        }
    }
    // 生成新容器
    NSArray *yiItems = [[huangliData.yi componentsSeparatedByString:@" "] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
    UIView *yiContainer = [self createItemsContainer:yiItems color:[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.1] textColor:[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0]];
    yiContainer.tag = 2001;
    [contentView addSubview:yiContainer];
    NSArray *jiItems = [[huangliData.ji componentsSeparatedByString:@" "] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"length > 0"]];
    UIView *jiContainer = [self createItemsContainer:jiItems color:[UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0] textColor:[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1.0]];
    jiContainer.tag = 2002;
    [contentView addSubview:jiContainer];
    // 重新布局
    if (yiTitle && yiContainer) {
        [yiContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(contentView).inset(16);
            make.top.equalTo(yiTitle.mas_bottom).offset(8);
        }];
    }
    if (jiTitle && jiContainer && yiContainer) {
        [jiTitle mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(contentView).offset(16);
            make.top.equalTo(yiContainer.mas_bottom).offset(0);
        }];
        [jiContainer mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(contentView).inset(16);
            make.top.equalTo(jiTitle.mas_bottom).offset(8);
        }];
    }
    [self.detailButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(contentView).inset(16);
        make.top.equalTo(jiContainer.mas_bottom).offset(16);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(contentView).offset(-16);
    }];
    
    // 重新启用动画
    [UIView setAnimationsEnabled:YES];
    
    // 强制立即布局
    [self.view layoutIfNeeded];
}

- (NSString *)formatNongliString:(NSString *)nongliString {
    if (!nongliString || nongliString.length == 0) {
        return nongliString;
    }
    
    // 示例: "乙巳年壬午月甲戌日属蛇周五第27周"
    // 目标: "乙巳年 壬午月 甲戌日\n属蛇 周 五 第 27周"
    
    NSMutableString *formattedString = [NSMutableString stringWithString:nongliString];
    
    // 1. 在年月日中间加空格
    // 找到"年"、"月"、"日"的位置并插入空格
    NSRange yearRange = [formattedString rangeOfString:@"年"];
    if (yearRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:yearRange.location + 1];
    }
    
    NSRange monthRange = [formattedString rangeOfString:@"月"];
    if (monthRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:monthRange.location + 1];
    }
    
    NSRange dayRange = [formattedString rangeOfString:@"日"];
    if (dayRange.location != NSNotFound) {
        // 在"日"后面换行
        [formattedString insertString:@"\n" atIndex:dayRange.location + 1];
    }
    
    // 2. 在第一个"周"字前加空格
    NSRange firstWeekRange = [formattedString rangeOfString:@"周"];
    if (firstWeekRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:firstWeekRange.location];
    }
    
    // 3. 在"第"字前加空格
    NSRange diRange = [formattedString rangeOfString:@"第"];
    if (diRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:diRange.location];
    }
    
    return formattedString;
}

- (NSString *)formatSecNongliString:(NSString *)nongliString {
    if (!nongliString || nongliString.length == 0) {
        return nongliString;
    }
    
    // 示例: "乙巳年壬午月甲戌日属蛇周五第27周"
    // 目标: "乙巳年 壬午月 甲戌日\n属蛇 周 五 第 27周"
    
    NSMutableString *formattedString = [NSMutableString stringWithString:nongliString];
    
    // 1. 在年月日中间加空格
    // 找到"年"、"月"、"日"的位置并插入空格
    NSRange yearRange = [formattedString rangeOfString:@"年"];
    if (yearRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:yearRange.location + 1];
    }
    
    NSRange monthRange = [formattedString rangeOfString:@"月"];
    if (monthRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:monthRange.location + 1];
    }
    
    NSRange dayRange = [formattedString rangeOfString:@"日"];
    if (dayRange.location != NSNotFound) {
        // 在"日"后面换行
        [formattedString insertString:@" " atIndex:dayRange.location + 1];
    }
    
    // 2. 在第一个"周"字前加空格
    NSRange firstWeekRange = [formattedString rangeOfString:@"周"];
    if (firstWeekRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:firstWeekRange.location];
    }
    
    // 3. 在"第"字前加空格
    NSRange diRange = [formattedString rangeOfString:@"第"];
    if (diRange.location != NSNotFound) {
        [formattedString insertString:@" " atIndex:diRange.location];
    }
    
    return formattedString;
}

#pragma mark - Date Control Actions

- (void)previousMonthTapped {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = -1;
    self.displayedMonth = [calendar dateByAddingComponents:components toDate:self.displayedMonth options:0];
    [self updateCalendarDisplay];
}

- (void)nextMonthTapped {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.month = 1;
    self.displayedMonth = [calendar dateByAddingComponents:components toDate:self.displayedMonth options:0];
    [self updateCalendarDisplay];
}

- (void)dateButtonTapped:(UIButton *)sender {
    NSInteger buttonIndex = [self.dateButtons indexOfObject:sender];
    if (buttonIndex == NSNotFound) return;
    
    // 获取按钮对应的日期
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:self.displayedMonth];
    components.day = 1;
    NSDate *firstDayOfMonth = [calendar dateFromComponents:components];
    
    NSInteger firstWeekday = [calendar component:NSCalendarUnitWeekday fromDate:firstDayOfMonth] - 1;
    NSInteger dayOffset = buttonIndex - firstWeekday;
    
    // 修正：使用 dateByAddingComponents:toDate:options: 替代 dateByAddingUnit:value:toDate:
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    offsetComponents.day = dayOffset;
    NSDate *selectedDate = [calendar dateByAddingComponents:offsetComponents toDate:firstDayOfMonth options:0];
    
    // 更新当前选中日期
    self.currentDate = selectedDate;
    [self loadHuangliDataForDate:self.currentDate];
    [self updateCalendarDisplay]; // 重新更新日历显示以反映选中状态
}

- (void)updateCalendarDisplay {
    // 更新月份年份标签
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy年MM月";
    self.monthYearLabel.text = [formatter stringFromDate:self.displayedMonth];
    
    // 获取当月第一天
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:self.displayedMonth];
    components.day = 1;
    NSDate *firstDayOfMonth = [calendar dateFromComponents:components];
    
    // 获取第一天是星期几（1=周日，2=周一...7=周六）
    // 转换为我们的索引（0=周日，1=周一...6=周六）
    NSInteger firstWeekday = [calendar component:NSCalendarUnitWeekday fromDate:firstDayOfMonth] - 1;
    
    // 获取当月天数
    NSRange daysInMonth = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self.displayedMonth];
    NSInteger numberOfDaysInMonth = daysInMonth.length;
    
    // 获取上个月的天数
    NSDateComponents *prevMonthComponents = [[NSDateComponents alloc] init];
    prevMonthComponents.month = -1;
    NSDate *previousMonth = [calendar dateByAddingComponents:prevMonthComponents toDate:self.displayedMonth options:0];
    NSRange daysInPreviousMonth = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:previousMonth];
    NSInteger numberOfDaysInPreviousMonth = daysInPreviousMonth.length;
    
    // 今天的日期
    NSDate *today = [NSDate date];
    
    // 更新所有日期按钮
    for (int i = 0; i < 42; i++) {
        UIButton *button = self.dateButtons[i];
        
        NSDate *buttonDate;
        NSString *dayText;
        BOOL isCurrentMonth = NO;
        
        if (i < firstWeekday) {
            // 上个月的日期
            NSInteger day = numberOfDaysInPreviousMonth - (firstWeekday - i - 1);
            dayText = [NSString stringWithFormat:@"%ld", (long)day];
            
            // 正确计算上个月日期
            NSDateComponents *prevComponents = [[NSDateComponents alloc] init];
            prevComponents.day = -(firstWeekday - i);
            buttonDate = [calendar dateByAddingComponents:prevComponents toDate:firstDayOfMonth options:0];
        } else if (i < firstWeekday + numberOfDaysInMonth) {
            // 当月的日期
            NSInteger day = i - firstWeekday + 1;
            dayText = [NSString stringWithFormat:@"%ld", (long)day];
            
            // 正确计算当月日期
            NSDateComponents *currentComponents = [[NSDateComponents alloc] init];
            currentComponents.day = day - 1;
            buttonDate = [calendar dateByAddingComponents:currentComponents toDate:firstDayOfMonth options:0];
            isCurrentMonth = YES;
        } else {
            // 下个月的日期
            NSInteger day = i - firstWeekday - numberOfDaysInMonth + 1;
            dayText = [NSString stringWithFormat:@"%ld", (long)day];
            
            // 正确计算下个月日期
            NSDateComponents *nextComponents = [[NSDateComponents alloc] init];
            nextComponents.day = i - firstWeekday;
            buttonDate = [calendar dateByAddingComponents:nextComponents toDate:firstDayOfMonth options:0];
        }
        
        [button setTitle:dayText forState:UIControlStateNormal];
        
        // 设置按钮样式
        if (isCurrentMonth) {
            // 当月日期
            [button setTitleColor:[UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
            
            // 检查是否是今天
            if ([calendar isDate:buttonDate inSameDayAsDate:today]) {
                button.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:0.1];
                [button setTitleColor:[UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0] forState:UIControlStateNormal];
            }
            
            // 检查是否是当前选中的日期
            if ([calendar isDate:buttonDate inSameDayAsDate:self.currentDate]) {
                button.backgroundColor = [UIColor colorWithRed:0.773 green:0.188 blue:0.188 alpha:1.0];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
        } else {
            // 其他月份的日期
            [button setTitleColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor clearColor];
        }
    }
}

- (void)previousDayTapped {
    // 保存当前滚动位置
    CGPoint currentOffset = self.scrollView.contentOffset;
    
    // 减少一天
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = -1;
    self.currentDate = [calendar dateByAddingComponents:components toDate:self.currentDate options:0];
    [self updateDateDisplay];
    [self loadHuangliDataForDate:self.currentDate];
    [self updateTodayButtonVisibility];
    
    // 恢复滚动位置
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.scrollView setContentOffset:currentOffset animated:NO];
    });
}

- (void)nextDayTapped {
    // 保存当前滚动位置
    CGPoint currentOffset = self.scrollView.contentOffset;
    
    // 增加一天
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.day = 1;
    self.currentDate = [calendar dateByAddingComponents:components toDate:self.currentDate options:0];
    [self updateDateDisplay];
    [self loadHuangliDataForDate:self.currentDate];
    [self updateTodayButtonVisibility];
    
    // 恢复滚动位置
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.scrollView setContentOffset:currentOffset animated:NO];
    });
}

- (void)todayTapped {
    // 回到今天
    self.currentDate = [NSDate date];
    [self updateDateDisplay];
    [self loadHuangliDataForDate:self.currentDate];
    [self updateTodayButtonVisibility];
    
    // 添加轻微的弹性动画
//    [UIView animateWithDuration:0.1 animations:^{
//        self.todayButton.transform = CGAffineTransformMakeScale(0.95, 0.95);
//    } completion:^(BOOL finished) {
//        [UIView animateWithDuration:0.1 animations:^{
//            self.todayButton.transform = CGAffineTransformIdentity;
//        }];
//    }];
}

- (void)updateDateDisplay {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"MM月dd日";
    NSString *dateString = [formatter stringFromDate:self.currentDate];
    
    // 添加年份（如果不是当前年）
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger currentYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger selectedYear = [calendar component:NSCalendarUnitYear fromDate:self.currentDate];
    
    if (currentYear != selectedYear) {
        formatter.dateFormat = @"yyyy年MM月dd日";
        dateString = [formatter stringFromDate:self.currentDate];
    }
    
    self.dateDisplayLabel.text = dateString;
    
    // 更新星期信息
    formatter.dateFormat = @"EEEE";
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    NSString *weekday = [formatter stringFromDate:self.currentDate];
    self.weekdayLabel.text = weekday;
}

- (void)updateTodayButtonVisibility {
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    BOOL isToday = [calendar isDate:self.currentDate inSameDayAsDate:[NSDate date]];
//    
//    [UIView animateWithDuration:0.3 animations:^{
//        self.todayButton.alpha = isToday ? 0.0 : 1.0;
//    }];
}

#pragma mark - Button Effects

- (void)buttonTouchDown:(UIButton *)button {
    [UIView animateWithDuration:0.1 animations:^{
        button.transform = CGAffineTransformMakeScale(0.9, 0.9);
        button.alpha = 0.7;
    }];
}

- (void)buttonTouchUp:(UIButton *)button {
    [UIView animateWithDuration:0.1 animations:^{
        button.transform = CGAffineTransformIdentity;
        button.alpha = 1.0;
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    // 更新渐变层frame
//    for (CALayer *layer in self.headerView.layer.sublayers) {
//        if ([layer isKindOfClass:[CAGradientLayer class]]) {
//            layer.frame = self.headerView.bounds;
//            break;
//        }
//    }
}

- (NSDate *)dateForButtonIndex:(NSInteger)index {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:self.displayedMonth];
    components.day = 1;
    NSDate *firstDayOfMonth = [calendar dateFromComponents:components];
    
    NSInteger firstWeekday = [calendar component:NSCalendarUnitWeekday fromDate:firstDayOfMonth] - 1;
    NSInteger dayOffset = index - firstWeekday;
    
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    offsetComponents.day = dayOffset;
    return [calendar dateByAddingComponents:offsetComponents toDate:firstDayOfMonth options:0];
}

@end

